<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
use Carbon\Carbon;


class User extends Authenticatable
{
    use Notifiable;
    use HasRoles;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password',
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    /** [setPassWordAttribute 修改器 修改密码] */
    public function setPassWordAttribute($value)
    {
        if(empty($value)){
            return;
        }else{
            if (strlen($value) !=60) {
            # 密码长度不为 60, 说明未被加密
                $value = bcrypt($value);
            }
            $this->attributes['password'] = $value;
        }
    }

    /** [contracts 用户与合约的关系] */
    public function contracts()
    {
        return $this->belongsToMany('App\Contract', 'user_contracts');
    }

    /**
     * [setContracts 设置合约]
     * @param [type] $contract_ids [数组]
     */
    public function setContracts($contract_ids)
    {
        if ( ! is_array($contract_ids)) {
            $contract_ids = compact($contract_ids);
        }

        $this->contracts()->sync($contract_ids);
    }

    /**
     * [unContracts 取消合约]
     * @param  [type] $contract_ids [数组]
     */
    public function unContracts($contract_ids)
    {
        if ( ! is_array($contract_ids)) {
            $contract_ids = compact($contract_ids);
        }

        $this->contracts()->detach($contract_ids);
    }


    /** [contractsTime 合约剩余天数] */
    public function contractsTime()
    {
        // 会员最新合约
        $contract = $this->contracts()->latest()->first();

        // 计算剩余天数
        return $contract ? $contract->cycle - Carbon::parse($contract->created_at)->diffInDays() : 0;
    }

    // 通过model_has_roles设置用户管理者
    public function roles()
    {
        return $this->morphToMany('App\Role','model','model_has_roles','model_id','role_id');
    }

    /** [products 产品] */
    public function products()
    {
        return $this->hasMany(Product::class);
    }

    /** [options 期权] */
    public function options()
    {
        return $this->hasManyThrough(Option::class, Product::class);
    }























}
